﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MAPDavy.Entities;
using MAPDavy.BusinessLogic;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

using System.IO;

namespace MAPDavy.WebMVC3.Controllers
{
    public class ConfigController : Controller
    {
        public ConfigController()
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                container.BuildUp(this.GetType(), this);
            }
        }

        [Dependency]
        public IAnioLectivoBL AnioLectivoBL { get; set; }

        [Dependency]
        public ILoaderBL LoaderBL { get; set; }

        //
        // GET: /Config/
        [Authorize]
        public ActionResult Index()
        {
            var anios = AnioLectivoBL.GetAllFromAnioLectivo();

            var an = from a in anios
                     select new { anio = a.Anio, desc = a.Descripcion, color = a.Color, a.Cerrado };

            return Json(an, JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "admin")]
        public ActionResult Loader()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult UploadConfig(HttpPostedFileBase userfile)
        {
            var cookie = Request.Cookies["workspace"];

            if (cookie == null)
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }

            var pathR = Path.Combine(Server.MapPath("~/files/" + cookie.Value.ToString()));

            if (!Directory.Exists(pathR))
            {
                Directory.CreateDirectory(pathR);
            }


            if (userfile != null && userfile.ContentLength > 0)
            {
                var fileDataName = "Loader_"+cookie.Value.ToString() + Path.GetExtension(userfile.FileName);
                pathR = Path.Combine(pathR, fileDataName);
                userfile.SaveAs(pathR);
            }

            var msg = new  { rpt = true};

            return Json(msg, JsonRequestBehavior.AllowGet);
        }

         [HttpPost]
         [Authorize(Roles = "admin")]
        public ActionResult ShowLoadData(bool complete=false)
        {
            if (complete)
            {
                var cookie = Request.Cookies["workspace"];

                if (cookie == null)
                {
                    var result = new
                    {
                        map = "",
                        exito = true,
                        msg = "La Sesion ha expirado"
                    };

                    return Json(result, JsonRequestBehavior.AllowGet);
                }

                var pathR = Path.Combine(Server.MapPath("~/files/" + cookie.Value.ToString()));
                var fileDataName = "Loader_" + cookie.Value.ToString() + ".xlsx";
                pathR = Path.Combine(pathR, fileDataName);

                var urlFile = "~/files/" + cookie.Value.ToString() + "/"+fileDataName;

                using (var document = SpreadsheetDocument.Open(pathR, true))
                {
                    try
                    {
                        var workbook = document.WorkbookPart.Workbook;
                        var workSheets = workbook.Descendants<Sheet>();

                        string sheetId = workSheets.First(s => s.Name == @"MAPTemplate").Id;
                        var sheet = (WorksheetPart)document.WorkbookPart.GetPartById(sheetId);

                        var sharedStringTable = document.WorkbookPart.SharedStringTablePart.SharedStringTable;
                        var maps = AnioLectivoBL.RetrieveMAPS(sheet.Worksheet, sharedStringTable);

                        var result = new 
                        {
                            map = maps,
                            exito = true,
                            msg = "",
                            count = maps.Count(),
                            urlFile = urlFile
                        };

                        Session["MapTemplate"] = maps;

                        return Json(result, JsonRequestBehavior.AllowGet);
                    }
                    catch
                    {
                        var result = new
                        {
                            map = "",
                            exito = false,
                            msg = "El documento to tiene el formato correcto."
                        };

                        return Json(result, JsonRequestBehavior.AllowGet);
                    }

                }
            }
            else
            {
                var result = new
                {
                    map = "",
                    exito = false,
                    msg = "El Archivo no ha sido cargado."
                };

                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
         public ActionResult RegistrarTutores(bool complete = false)
         {
             if (Session["MapTemplate"] ==null)
             {
                 var error = new
                 {
                     afectados = 0,
                     exito = false,
                     msg = "La Sesión a Expirado vuelva a Cargar el archivo."
                 };

                 return Json(error, JsonRequestBehavior.AllowGet);
             }             

             try
             {
                 var maps = Session["MapTemplate"] as List<MAPTemplate>;

                 var afec = LoaderBL.RegistrarTutores(maps);
                 
                 var result = new
                 {
                     afectados = afec,
                     exito = true,
                     msg = string.Format("Tutores Nuevos Registrados: {0}",afec)
                 };

                 return Json(result, JsonRequestBehavior.AllowGet);
             }
             catch (Exception ex)
             {
                 var error = new
                 {
                     afectados = 0,
                     exito = false,
                     msg = ex.Message
                 };

                 return Json(error, JsonRequestBehavior.AllowGet);
             }
         }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult AsignarTutores(bool complete = false)
        {
            if (Session["MapTemplate"] == null)
            {
                var error = new
                {
                    afectados = 0,
                    exito = false,
                    msg = "La Sesión a Expirado vuelva a Cargar el archivo."
                };

                return Json(error, JsonRequestBehavior.AllowGet);
            }

            try
            {
                var maps = Session["MapTemplate"] as List<MAPTemplate>;

                var afec = LoaderBL.AsignarTutores(maps);

                var result = new
                {
                    afectados = afec,
                    exito = true,
                    msg = string.Format("Tutores Asignados a una Sección: {0}", afec)
                };

                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                string msg = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                
                var error = new
                {
                    afectados = 0,
                    exito = false,
                    msg = msg
                };

                return Json(error, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult RegistrarStudents(bool complete = false)
        {
            if (Session["MapTemplate"] == null)
            {
                var error = new
                {
                    afectados = 0,
                    exito = false,
                    msg = "La Sesión a Expirado vuelva a Cargar el archivo."
                };

                return Json(error, JsonRequestBehavior.AllowGet);
            }

            try
            {
                var maps = Session["MapTemplate"] as List<MAPTemplate>;

                var afec = LoaderBL.RegistrarStudents(maps);

                var result = new
                {
                    afectados = afec,
                    exito = true,
                    msg = string.Format("Nuevos Alumnos Registrados: {0}", afec)
                };

                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                var error = new
                {
                    afectados = 0,
                    exito = false,
                    msg = ex.Message
                };

                return Json(error, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult MatricularStudents(bool complete = false)
        {
            if (Session["MapTemplate"] == null)
            {
                var error = new
                {
                    afectados = 0,
                    exito = false,
                    msg = "La Sesión a Expirado vuelva a Cargar el archivo."
                };

                return Json(error, JsonRequestBehavior.AllowGet);
            }

            try
            {
                var maps = Session["MapTemplate"] as List<MAPTemplate>;

                var afec = LoaderBL.MatricularStudents(maps);

                var result = new
                {
                    afectados = afec,
                    exito = true,
                    msg = string.Format("Alumnos Matriculados: {0}", afec)
                };

                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                var error = new
                {
                    afectados = 0,
                    exito = false,
                    msg = ex.Message
                };

                return Json(error, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        [Authorize]
        public ActionResult Workspace(int anio = 0)
        {
            if (anio != 0)
            {
                var an = AnioLectivoBL.GetAnioLectivoByAnio(anio.ToString());

                if (an==null)
                {
                   return Json(false, JsonRequestBehavior.AllowGet); 
                }

                Response.Cookies["cerrado"].Value = an.Cerrado.ToString().ToLower();
                Response.Cookies["cerrado"].Path = "/";
                Response.Cookies["cerrado"].Expires = DateTime.Now.AddDays(365);

                Response.Cookies["workspace"].Value = an.Anio;
                Response.Cookies["workspace"].Path = "/";
                Response.Cookies["workspace"].Expires = DateTime.Now.AddDays(365);

                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            
        }
    }

}
